<template>
	<div>
		<div class="search-bar">
			<el-input placeholder="搜索学生" v-model="searchQuery" @keyup.enter="handleSearch" />
			<el-button type="text" @click="handleSearch">搜索</el-button>
		</div>

		<el-table :data="paginatedStudents" style="width: 100%">
			<el-table-column prop="sname" label="姓名">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.sname)"></span>
				</template>
			</el-table-column>

			<el-table-column prop="sid" label="学号">
				<template #default="scope">
					<span v-html="highlightMatch(scope.row.sid)"></span>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
import fuzzy from 'fuzzy';

export default {
	data() {
		return {
			searchQuery: '',
			students: [
				{ sname: "张三", sid: "20231001" },
				{ sname: "李四", sid: "20231002" },
				{ sname: "王五", sid: "20231003" },
				{ sname: "赵六", sid: "20231004" },
				{ sname: "陈七", sid: "20231005" }
			],
			paginatedStudents: []
		};
	},
	methods: {
		handleSearch() {
			const searchResults = fuzzy.filter(this.searchQuery, this.students, {
				extract: student => `${student.sname} ${student.sid}`
			});

			this.paginatedStudents = searchResults.map(result =>
					this.students.find(student => student.sid === result.original.sid)
			);
		},
		highlightMatch(text) {
			if (!this.searchQuery) return text;
			const regex = new RegExp(this.searchQuery, 'gi');
			return text.replace(regex, '<span class="highlight">$&</span>');
		}
	},
	created() {
		this.paginatedStudents = [...this.students];
	}
};
</script>

<style scoped>
.highlight {
	color: red;
}
.search-bar {
	margin-bottom: 20px;
}
</style>

